package org.kabeja.parser;

import org.kabeja.parser.table.DXFTableHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shutao
 * @since 2022/4/25 14:29
 */
public class DXFTableSectionHandler extends AbstractSectionHandler implements HandlerManager {
    public static final String SECTION_KEY = "TABLES";
    public static final String TABLE_START = "TABLE";
    public static final String TABLE_END = "ENDTAB";
    public final int TABLE_CODE = 0;
    private String table = "";
    private DXFTableHandler handler;
    private Map<String, Object> handlers = new HashMap<>();
    private boolean parse = false;

    public DXFTableSectionHandler() {
    }

    @Override
    public String getSectionKey() {
        return SECTION_KEY;
    }

    @Override
    public void parseGroup(int var1, DXFValue var2) {
        if (var1 == 0) {
            if ("ENDTAB".equals(var2.getValue())) {
                this.table = "";
                if (this.parse) {
                    this.handler.endParsing();
                    this.parse = false;
                }
            } else if (!"TABLE".equals(var2.getValue())) {
                if (this.parse) {
                    this.handler.endParsing();
                }

                this.table = var2.getValue();
                if (this.handlers.containsKey(this.table)) {
                    this.handler = (DXFTableHandler)this.handlers.get(this.table);
                    this.handler.setDXFDocument(this.doc);
                    this.handler.startParsing();
                    this.parse = true;
                } else {
                    this.parse = false;
                }
            }
        } else if (this.parse) {
            this.handler.parseGroup(var1, var2);
        }

    }

    @Override
    public void endSection() {
    }

    @Override
    public void startSection() {
        this.parse = false;
    }

    @Override
    public void addHandler(Handler var1) {
        this.addDXFTableHandler((DXFTableHandler)var1);
    }

    public void addDXFTableHandler(DXFTableHandler var1) {
        this.handlers.put(var1.getTableKey(), var1);
    }

    @Override
    public void releaseDXFDocument() {
        this.doc = null;

        for (Object o : this.handlers.values()) {
            Handler var2 = (Handler) o;
            var2.releaseDXFDocument();
        }

    }
}